// Time Routines

#ifndef _TIME_C_
#define _TIME_C_

// RTC is run on Timer1
// set to one tick per second
// Assumes 16MHz clock
//   Fosc = 4MHz
//   Low byte of timer divides by 256 giving 15625 counts per second into High byte
//   High byte divides by 125, giving 125 counts per second (125*125 = 15625)
//   To get counter to divide by 125 preload High byte with 256-125 = 131
//   OS tick is generated on rollover = 15625/125 = 125Hz = 8mS

// T1CON
// 0bWRWW WWWW
//   |||| |||+-- 1=Enable Timer1, 0=Disable
//   |||| ||+--- 1=External clock, 0=Internal (Fosc)
//   |||| |+---- 1=No external sync, 0=External sync (ignored for Fosc)
//   |||| +----- 1=TMR1 osc enabled, 0=Disabled
//   ||++------- Prescaler: 11=1:8, 10=1:4, 01=1:2, 00=1:1 
//   |+--------- Main system clock source 
//   +---------- 1=16 bit operation, 0=8 bit operation

#define TMR1_PRELOAD		131
#define TMR1_SECOND		124

char time_second;
char count;
char tick;

void time_config( void )
{
	T1CON = 0b00100001;
	TMR1IP = 0;	// low priority interrupt
	TMR1H = TMR1_PRELOAD;
} 

// we should get here within 256 instructions of the interrupt
// so we can assume we have time to modify the high byte preload
// without causing a glitch should the low byte value roll over
void isr_time( void )
{
   tick++;
	TMR1IF = 0;
	TMR1H = TMR1_PRELOAD;
	
	if( ++count >= TMR1_SECOND )
	{
		time_second++;
		count = 0;
	}		
}
	
#endif